<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row :gutter="24" class="card-container">
                <el-col :span="2"></el-col>
                <el-col :span="20">
                    <el-steps :active="active" finish-status="success">
                        <el-step :title="$t('device.deviceConfig')" />
                        <el-step :title="$t('device.driverConfig')" />
                        <el-step :title="$t('device.pointConfig')" />
                    </el-steps>
                </el-col>
            </el-row>

            <el-divider />

            <!-- 编辑信息配置 -->
            <el-form v-if="active == 0" ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px"
                v-loading="loading">
                <el-row>
                    <el-col>
                        <el-form-item :label="$t('device.name')" prop="name">
                            <el-input v-model="form.name" disabled :placeholder="$t('device.inputNameTip')" />
                        </el-form-item>
                        <el-form-item :label="$t('product.name')" prop="productId">
                            <el-select v-model="form.productId" disabled :placeholder="$t('product.inputCategoryIdTip')">
                                <el-option v-for="(item, index) in productList" :key="index" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('device.location')" prop="location">
                            <el-input v-model="form.location" :placeholder="$t('device.inputLocationTip')" />
                        </el-form-item>
                        <el-form-item :label="$t('device.status')" prop="status">
                            <el-select v-model="form.status" :placeholder="$t('device.selectStatusTip')">
                                <el-option v-for="(item, index) in device_status_temp" :key="index" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('device.remark')" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :placeholder="$t('device.inputRemarkTip')"
                                :autosize="{ minRows: 2, maxRows: 4 }" />
                        </el-form-item>

                        <el-form-item :label="$t('device.cron')" prop="cron">
                            <el-select v-model="form.cron" :placeholder="$t('device.inputCornTip')">
                                <el-option v-for="(item, index) in cron" :key="index" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <ModbusTcp v-if="protocol.protocol == 'MODBUS_TCP'" :product-id="form.productId" :device-id="form.id" ref="formDialogRef"
                :driverValue="form.driverValue" v-model:active="active">
                <template #button>
                    <div style="text-align: center; margin-top: 10px;">
                        <div v-if="active == 3">
                            <el-button @click="router.back()">{{ $t('device.down') }}</el-button>
                        </div>

                        <div v-else>
                            <el-button v-show="active != 0" @click="active--">{{ $t('device.pre') }}</el-button>
                            <el-button v-show="active == 2" @click="formDialogRef.editPoint()">{{ $t('device.edit')
                            }}</el-button>
                            <el-button v-show="active == 0" @click="next">{{ $t('device.next') }}</el-button>
                            <el-button v-show="active != 0" @click="formDialogRef.next(active)">{{ $t('device.next')
                            }}</el-button>
                        </div>
                    </div>
                </template>
            </ModbusTcp>

            <Mqtt v-if="protocol.protocol == 'MQTT'" :product-id="form.productId" :device-id="form.id" ref="formDialogRef"
                :driverValue="form.driverValue" v-model:active="active">
                <template #button>
                    <div style="text-align: center; margin-top: 10px;">
                        <div v-if="active == 3">
                            <el-button @click="router.back()">{{ $t('device.down') }}</el-button>
                        </div>

                        <div v-else>
                            <el-button v-show="active != 0" @click="active--">{{ $t('device.pre') }}</el-button>
                            <el-button v-show="active == 2" @click="formDialogRef.editPoint()">{{ $t('device.edit')
                            }}</el-button>
                            <el-button v-show="active == 0" @click="next">{{ $t('device.next') }}</el-button>
                            <el-button v-show="active != 0" @click="formDialogRef.next(active)">{{ $t('device.next')
                            }}</el-button>
                        </div>
                    </div>
                </template>
            </Mqtt>

            <OpcUa v-if="protocol.protocol == 'OPC_UA'" :product-id="form.productId" :device-id="form.id" ref="formDialogRef"
                :driverValue="form.driverValue" v-model:active="active">
                <template #button>
                    <div style="text-align: center; margin-top: 10px;">
                        <div v-if="active == 3">
                            <el-button @click="router.back()">{{ $t('device.down') }}</el-button>
                        </div>

                        <div v-else>
                            <el-button v-show="active != 0" @click="active--">{{ $t('device.pre') }}</el-button>
                            <el-button v-show="active == 2" @click="formDialogRef.editPoint()">{{ $t('device.edit')
                            }}</el-button>
                            <el-button v-show="active == 0" @click="next">{{ $t('device.next') }}</el-button>
                            <el-button v-show="active != 0" @click="formDialogRef.next(active)">{{ $t('device.next')
                            }}</el-button>
                        </div>
                    </div>
                </template>
            </OpcUa>
        </div>
    </div>
</template>

<script setup lang="ts" name="deviceEdit">
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { getObj, putObj } from '/@/api/device/device';
import { fetchList } from '/@/api/device/product';


// 引入组件
const ModbusTcp = defineAsyncComponent(() => import('./driver/modbustcp.vue'));
const Mqtt = defineAsyncComponent(() => import('./driver/mqtt.vue'));
const OpcUa = defineAsyncComponent(() => import('./driver/opcUa.vue'));

// 获取设备状态字典
const { device_status, cron } = useDict('device_status', 'cron');
const device_status_temp = ref(
  JSON.parse(JSON.stringify(device_status.value))
);
// 去除在线、离线状态
device_status_temp.value.splice(3, 2);

// 使用国际化插件
const { t } = useI18n();

// 定义变量内容
const dataFormRef = ref();
const active = ref(0);
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const productList = ref([{ label: '', value: '' }]);
const formDialogRef = ref();
const protocol = ref({}) as any;


// 提交表单数据
const form = reactive({
    id: '',
    name: '',
    orderNum: 0,
    longitude: '',
    latitude: '',
    location: '',
    cron: '',
    remark: '',
    status: '0',
    productId: '',
    driverValue: ''
});
// 定义校验规则
const dataRules = ref({
    name: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
    productId: [{ required: true, message: '产品id不能为空', trigger: 'blur' }],
    location: [{ required: true, message: '地理位置不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '设备状态不能为空', trigger: 'blur' }],
});

/**
 * 进度条向后一步
 */
const next = async () => {
    if (active.value < 3) {
        active.value++;
    }

    const valid = await dataFormRef.value.validate().catch(() => { });
    if (!valid) return false;

    try {
        loading.value = true;
        await putObj(form);
        useMessage().success(t('common.editSuccessText'));
    } catch (err: any) {
        useMessage().error(err.msg);
    } finally {
        loading.value = false;
    }
}


// 在页面加载前调用接口
onMounted(() => {
    loading.value = true;
    // 获取设备数据
    getObj({ id: route.query?.id })
        .then((res: any) => {
            Object.assign(form, res.data[0]);

            // 获取产品下拉框
            fetchList({ size: 9999 }).then(resp => {
                productList.value = resp.data!.records.map((item: { name: string; id: string; protocol: string; }) => ({ label: item.name, value: item.id, protocol: item.protocol }));
                protocol.value = productList.value.find(item => item.value == form.productId);
            });
        })
        .finally(() => {
            loading.value = false;
        });
});
</script>